package controllers

import (
	"fmt"
	"github.com/astaxie/beego"
	"net/http"
	"strings"
)

type baseController struct {
	beego.Controller
	controllerName string
	actionName     string
}

func (this *baseController) Prepare() {
	controllerName, actionName := this.GetControllerAndAction()
	this.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10])
	this.actionName = strings.ToLower(actionName)
}

//模板展示
func (this *baseController) Display(tpl ...string) {
	var tplname string
	if len(tpl) == 1 {
		tplname = tpl[0] + ".html"
	} else {
		tplname = this.controllerName + "/" + this.actionName + ".html"
	}
	this.TplName = tplname
}

//是否ajax请求
func (this *baseController) IsAjax() bool {
	return this.Ctx.Input.IsAjax()
}

//是否post提交
func (this *baseController) IsPost() bool {
	return this.Ctx.Request.Method == "POST"
}

//返回结果
func (this *baseController) Rsp(status int, msg string) {
	this.Data["json"] = map[string]interface{}{"status": status, "message": msg}
	this.ServeJSON()
}

//返回结果,带data
func (this *baseController) RspData(status int, msg string, data string) {
	this.Data["json"] = map[string]interface{}{"status": status, "message": msg, "data": data}
	this.ServeJSON()
}

//下载文件
func (this *baseController) DownloadFile(path string, filename string) {
	this.Ctx.Output.Header("Accept-Ranges", "bytes")
	this.Ctx.Output.Header("Content-Disposition", "attachment; filename="+fmt.Sprintf("%s", filename)) //文件名
	this.Ctx.Output.Header("Cache-Control", "must-revalidate, post-check=0, pre-check=0")
	this.Ctx.Output.Header("Pragma", "no-cache")
	this.Ctx.Output.Header("Expires", "0")

	//输出文件到浏览器
	http.ServeFile(this.Ctx.ResponseWriter, this.Ctx.Request, path)
}
